﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using CSharpHelpers.IOs;
using log4net.Config;

namespace CSharpHelpers.Winforms
{
    class FormHelper
    {
        /// <summary>
        /// 切换窗体界面
        /// @author john add by 2013-07-12
        /// </summary>
        /// <param name="frm"></param>
        public static void ExChangeForm(Form fromForm, Form toForm, Form parentForm)
        {
            if (fromForm != null && toForm != null)
            {
                if (parentForm != null)
                {
                    parentForm.IsMdiContainer = true;
                    toForm.MdiParent = parentForm;
                }

                toForm.WindowState = FormWindowState.Maximized;
                toForm.ControlBox = false;
                //toForm.Dock = DockStyle.None;

                try
                {
                    toForm.Show();
                }
                catch (Exception e)
                {
                    SystemLog.Error("切換窗體異常: " + e);
                    //throw;
                }

                //fromForm.Hide();
                fromForm.Close();
                fromForm.Dispose();
            }
        }

        /// <summary>
        /// X屏幕中
        /// </summary>
        /// <param name="pbList"></param>
        public static void SetPictureLoctionX(params Control[] pbList)
        {
            int x = 0;
            foreach (Control pb in pbList)
            {
                x = pb.Width / 2;
                x = 1280 / 2 - x;
                pb.Location = new Point(x, pb.Location.Y);
            }
        }

        /// <summary>
        /// Y屏幕中
        /// </summary>
        /// <param name="pbList"></param>
        public static void SetPictureLoctionY(params Control[] pbList)
        {
            int y = 0;
            foreach (Control pb in pbList)
            {
                y = pb.Height / 2;
                y = 1024 / 2 - y;
                pb.Location = new Point(pb.Location.X, y);
            }
        }

        /// <summary>
        /// 檢查程序是否已經運行
        /// </summary>
        /// <returns></returns>
        private static bool IsDuplicateProcess()
        {
            int processCount = 0;
            Process[] pa = Process.GetProcesses();//获取当前进程数组。
            foreach (Process PTest in pa)
            {
                if (PTest.ProcessName == Process.GetCurrentProcess().ProcessName)
                {
                    processCount += 1;
                }
            }
            return processCount > 1;
        }

        /// <summary>
        /// 檢查是否成功連接數據庫
        /// </summary>
        /// <returns></returns>
        private static bool CheckConnection()
        {
            //if (new Access().IsConnectedDB() == false)
            //{
            //    return false;
            //}

            return true;
        }

        private void Main()
        {
            XmlConfigurator.Configure(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "/log4net.config"));

            // 注册全局线程异常处理事件侦听
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
        }

        /// <summary>
        /// 全局线程异常处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            SystemLog.Error(e.Exception);
            var msg = e.Exception.Message;
            if (e.Exception.Message.Contains("Execute Sql Error"))
            {
                msg = "Can not connect to database";
            }

            MessageBox.Show("Error:" + msg);
        }

        static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                SystemLog.Error(((Exception)e.ExceptionObject));
                MessageBox.Show("Unhandled Exception EventHandler:" + ((Exception)e.ExceptionObject).Message);
            }
            catch (Exception ex)
            {
                SystemLog.Error(ex);
            }
        }

        public static void DisposeForm(Form frm)
        {
            if (frm != null && !frm.IsDisposed)
            {
                try
                {
                    frm.Close();
                    frm.Dispose();
                }
                catch { }
            }
        }

        #region CheckedListBox
        public static void BindCheckedListBox(CheckedListBox box, Dictionary<int, string> dic, string report = "")
        {
            BindingSource bs = new BindingSource();
            bs.DataSource = dic;
            box.DataSource = bs;
            box.DisplayMember = "Value";   //要显示的属性名
            box.ValueMember = "Key"; //存储的属性名
            bool isChecked = false;

            for (int i = 0; i < box.Items.Count; i++)
            {
                KeyValuePair<int, string> pair = (KeyValuePair<int, string>)box.Items[i];
                string value = "," + pair.Key.ToString() + ",";
                if (report == ",All,")
                {
                    isChecked = true;
                }
                else
                {
                    if (report.Contains(value))
                        isChecked = true;
                    else
                        isChecked = false;
                }
                box.SetItemChecked(i, isChecked);
            }
        }

        public static string GetCheckedListBoxByIntValues(CheckedListBox box)
        {
            string str = string.Empty;
            for (int i = 0; i < box.CheckedItems.Count; i++)
            {
                KeyValuePair<int, string> items = (KeyValuePair<int, string>)box.CheckedItems[i];
                str += items.Key + ",";
            }
            if (str != String.Empty)
            {
                str = str.Substring(0, str.Length - 1);
            }
            return str;
        }

        public static string GetCheckedListBoxByValues(CheckedListBox box)
        {
            string str = string.Empty;
            for (int i = 0; i < box.CheckedItems.Count; i++)
            {
                KeyValuePair<string, string> items = (KeyValuePair<string, string>)box.CheckedItems[i];
                str += items.Value + ",";
            }
            if (str != String.Empty)
            {
                str = str.Substring(0, str.Length - 1);
            }
            return str;
        }

        public static List<string> GetCheckedListBoxKey(CheckedListBox box)
        {
            List<string> listValue = new List<string>();

            for (int i = 0; i < box.CheckedItems.Count; i++)
            {
                KeyValuePair<int, string> items = (KeyValuePair<int, string>)box.CheckedItems[i];
                listValue.Add(items.Key.ToString());
            }
            return listValue;
        }

        #endregion

        #region listview
        /// <summary>
        /// ListView绑定数据
        /// </summary>
        /// <param name="box">需要绑定的ListView</param>
        /// <param name="dic">数据的集合(ID,Name)</param>
        /// <param name="report">需要选的项目的ID的集合</param>
        /// <param name="header">ListView第一列的表头</param>
        /// <param name="width">ListView第一列的列宽</param>
        public static void BindListView(ListView box, Dictionary<int, string> dic, string report, string header, int width)
        {
            box.Items.Clear();
            box.Columns.Clear();
            box.CheckBoxes = true;
            box.View = View.Details;
            box.Columns.Add(header, width);
            foreach (KeyValuePair<int, string> k in dic)
            {
                box.Items.Add(k.Value, k.Key);
            }
            bool isChecked = false;

            for (int i = 0; i < box.Items.Count; i++)
            {

                string value = "," + box.Items[i].ImageIndex + ",";
                if (report.Contains(value))
                    isChecked = true;
                else
                    isChecked = false;
                box.Items[i].Checked = isChecked;
            }
        }

        /// <summary>
        /// 获得ListView选中项ID的集合
        /// </summary>
        /// <param name="box">ListView控件</param>
        /// <returns>ListView选中项ID的集合</returns>
        public static List<string> GetListViewKey(ListView box)
        {
            List<string> listValue = new List<string>();

            for (int i = 0; i < box.Items.Count; i++)
            {
                if (box.Items[i].Checked == true)
                    listValue.Add(box.Items[i].ImageIndex.ToString());
            }
            return listValue;
        }

        #endregion

    }
}
